package com.cjjd.c.utils;

import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.cjjd.c.App;


/**
 * 1. 使改变ui的操作运行在主线程
 * 2. 获取string、color、drawable等资源
 * 3. 重新设置listview的高度
 */
public class CommonUtil {

    public static void runOnUIThread(Runnable runnable) {
        App.getMainHandler().post(runnable);

    }

    public static String getString(int resId) {
        // resId = R.string.tip
        return App.getContext().getString(resId);
    }

    public static int getColor(int resId) {
        // resId = R.string.tip
        return App.getContext().getResources().getColor(resId);
    }

    public static Drawable getDrawable(int resId) {
        return App.getContext().getResources().getDrawable(resId);
    }

    /**
     * 重新设置listview的高度
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        if (listView.getDivider() != null) {
            params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        } else {
            params.height = totalHeight;
        }
        params.height = totalHeight + listView.getPaddingTop() + listView.getPaddingBottom();
        LogUtil.e("xyd", "height is " + params.height);
        listView.setLayoutParams(params);
    }

}
